#/usr/bin/env python3
import os

class Config:
    dirs = []
    conf = {}
    def __init__(self):
        self.init_config()
        self.read_config()

    def init_config(self):
        self.cur_dir = os.path.dirname(__file__)
        self.dirs.append(os.path.join(self.cur_dir, "../web/"))
        self.listen_port = 80
        self.listen_ip = '0.0.0.0'

    def get(self, key):
        conf_value = None
        try:
            conf_value = self.conf[key]
        except:
            pass
        return conf_value

    def read_config(self):
        config_file = os.path.join(self.cur_dir, "config.ini")
        print("config file is", config_file)
        if os.path.isfile(config_file):
            with open(config_file) as cfile:
                while True:
                    cline = cfile.readline()
                    if cline:
                        if cline[0] == "#" or cline[0] == "\n":
                            continue
                        self.process(cline)
                    else:
                        break
        print(self.conf)
    
    def process(self, cline):
        if "directory=" in cline:
            self.dirs.clear()
            conf = cline[cline.find("=")+1:].strip().split(":")
            for c in conf:
                if c[0] == "/" and os.path.isdir(c):
                    self.dirs.append(c)
                else:
                    d = os.path.abspath(os.path.join(self.cur_dir, c))
                    if os.path.isdir(d):
                        self.dirs.append(d)
            print(self.dirs)
        elif "listen_ip=" in cline:
            self.listen_ip = cline[cline.find("=")+1:]
        elif "listen_port=" in cline:
            self.listen_port = int(cline[cline.find("=")+1:])
            if self.listen_port == 0:
                self.listen_port = 80
        else:
            key = cline[:cline.find("=")]
            value = cline[cline.find("=")+1:]
            if value != "\n":
                self.conf[key] = value.strip()

    def dump_config(self):
        pass

if __name__ == "__main__":
    c = Config()
    c.dump_config()
